package http;


import http.config.HttpConfig;
import http.interceptor.InterceptorUtil;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by yemao on 2017/3/23.
 * 网络请求工厂类
 */

public class RetrofitFactory {
    private APIFunction mApiFunction;
    private static RetrofitFactory mRetrofitFactory;

    private RetrofitFactory() {
        Retrofit retrofit =  getRetrofit();
        mApiFunction = retrofit.create(APIFunction.class);

    }

    /**
     * 带baseurl的retrofit
     *
     * @return
     */
    public static RetrofitFactory getInstence() {
        if (mRetrofitFactory == null) {
            synchronized (RetrofitFactory.class) {
                if (mRetrofitFactory == null)
                    mRetrofitFactory = new RetrofitFactory();
            }
        }
        return mRetrofitFactory;
    }


    public APIFunction API() {
        return mApiFunction;
    }

    /**
     * 设置retrofit
     *
     * @return
     */
    private Retrofit getRetrofit() {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .readTimeout(HttpConfig.TIME, TimeUnit.SECONDS)
                .writeTimeout(HttpConfig.TIME, TimeUnit.SECONDS)
                .connectTimeout(HttpConfig.TIME, TimeUnit.SECONDS)
                .addInterceptor(InterceptorUtil.getHeaderInterceptor())
                .addInterceptor(InterceptorUtil.getLogInterceptor())
                .build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(HttpConfig.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(okHttpClient)
                .build();
        return retrofit;
    }
}
